const SendService = require('../service/sendRecordService');
const WorkerService = require('../service/worker');
const TenantService = require('../service/tenant');
const NoticeService = require('../service/notice');
const moment = require('moment');
const { logger } = require('../utils');

const sendService = new SendService();
const workerService = new WorkerService();
const tenantService = new TenantService();
const noticeService = new NoticeService();

module.exports = app => {
  async function getList(req, res) {
    const { body = {}, userInfo } = req;
    const { status, tenantId, limit, offset, needTenantInfo, workerId } = body;
    if (userInfo) {
      const param = {};
      if (tenantId) {
        param.tenantId = tenantId;
      }
      if (workerId) {
        param.workerId = workerId;
      }
      if (status) {
        param.status = status;
      }

      const list = await sendService.search({
        where: param,
        offset:offset||0,
        limit:limit||10,
      });
      const totalCount = await sendService.searchCount(param);
      const sendRecords = [];
      if (list?.length) {
        if (needTenantInfo) {
          // 需要用工单位信息
          await Promise.all(
            list.map(record =>
              tenantService.find(record.tenantId).then(tenant => {
                if (tenant) {
                  sendRecords.push({
                    ...record,
                    tenantName: tenant.name,
                  });
                }
              }),
            ),
          );
        }
      }
      res.json({
        code: 20000,
        data: {
          list: sendRecords,
          totalCount: totalCount,
        },
      });
      return;
    }
    res.json({
      code: 50204,
      message: '用户登录已过期，请退出重试',
    });
  }
  app.post(`${process.env.VUE_APP_BASE_API}/send/list`, getList);
  app.post(`${process.env.VUE_APP_M_BASE_API}/send/list`, getList);

  app.post(`${process.env.VUE_APP_BASE_API}/send/create`, async (req, res) => {
    const { userInfo, body } = req;
    if (userInfo) {
      const sendCreated = await sendService.batchCreate(body);
      const workerUpdated = await workerService.batchUpdate(body.workers.map(workerItem => ({
        id: workerItem.id,
        status: 'SEND',
        contractId: workerItem.contractId,
        contractName: workerItem.contractName,
        contractStatus: workerItem.contractStatus,
        deadline: workerItem.deadline,
      })));
      try {
        // 消息推送
        const { startTime, endTime, workers = [] } = body;
        const tenantItem = await tenantService.find(body.tenantId);
        workers.forEach(worker => {
          const tempDays = moment(endTime).diff(moment(startTime), 'days');
          let time;
          if (tempDays < 0) {
            time = `${0}天`;
          } else if (tempDays === 0) {
            time = `${moment(endTime).diff(moment(startTime), 'hours')}小时`;
          } else if (tempDays < 365) {
            time = `${tempDays}天`;
          } else {
            time = `${(tempDays / 365).toFixed(2)}年`;
          }
          noticeService.addNotice({
            message: `【工人派遣】${worker.name} -> ${tenantItem.name}，期限${time}`,
            organizationId: userInfo.organizationId,
          });
        });
      } catch (e) {
        logger.error({
          category: 'notice',
          workers: body.workers,
        });
      }
      if (sendCreated) {
        return res.json({
          code: 20000,
          data: { created: sendCreated, workerUpdated },
        });
      }
      return res.json({
        code: 500,
        message: '派遣添加失败',
      });
    }
    res.json({
      code: 50204,
      message: '用户登录已过期，请退出重试',
    });
  });

  app.post(`${process.env.VUE_APP_BASE_API}/send/update`, async (req, res) => {
    const { body, userInfo } = req;
    const { Id } = body;
    if (userInfo) {
      const status = await sendService.update(Id, body);
      if (status) {
        return res.json({
          code: 20000,
          data: { Id },
        });
      }
      return res.json({
        code: 500,
        message: '修改工人信息失败',
      });
    }
    res.json({
      code: 50204,
      message: '用户登录已过期，请退出重试',
    });
  });

  app.post(`${process.env.VUE_APP_BASE_API}/send/batchUpdate`, async (req, res) => {
    const { body, userInfo } = req;
    if (userInfo) {
      const status = await sendService.batchUpdate(body.List);
      if (status) {
        return res.json({
          code: 20000,
          data: { Ids: body.List.map(v => v.Id) },
        });
      }
      return res.json({
        code: 500,
        message: '修改派遣信息失败',
      });
    }
    res.json({
      code: 50204,
      message: '用户登录已过期，请退出重试',
    });
  });
  app.post(`${process.env.VUE_APP_M_BASE_API}/send/listForHome`, async (req, res) => {
    const { body = {}, userInfo } = req;
    const { workerId } = body;
    if (userInfo) {
      const param = {};
      if (workerId) {
        param.workerId = workerId;
      }
      let list = await sendService.search({where:param});

      const sendRecords = [];
      if (list?.length) {
        const recordInService = list.find(v => (new Date(v.startTime) <= new Date()) && (new Date(v.endTime) > new Date()));// 服务中
        const pageList = recordInService ? [recordInService] : list.slice(0, 1);
        // 需要用工单位信息
        await Promise.all(
          pageList.map(record =>
            tenantService.find(record.tenantId).then(tenant => {
              if (tenant) {
                sendRecords.push({
                  ...record,
                  tenantName: tenant.name,
                });
              }
            }),
          ),
        );
      }
      res.json({
        code: 20000,
        data: {
          list: sendRecords,
        },
      });
      return;
    }
    res.json({
      code: 50204,
      message: '用户登录已过期，请退出重试',
    });
  });
};
